package com.lzgcoding.onlineshopapp.feature.detail

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lzgcoding.onlineshopapp.room.dao.ItemDao
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update

class DetailViewModel(
    private val itemDao: ItemDao,
    private val productId: Int
) : ViewModel() {
    private val _uiState = MutableStateFlow(DetailUIState())
    val uiState = _uiState.onStart {
        initData()
    }.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        _uiState.value
    )

    private suspend fun initData() {
        val product = itemDao.getItemById(productId)
        _uiState.update {
            it.copy(
                product = product,
                selectedSize = product?.sizes?.first(),
                selectedColor = product?.colors?.first(),
            )
        }
    }

    fun onSizeChange(size: String) {
        _uiState.update {
            it.copy(selectedSize = size)
        }
    }

    fun onColorChange(color: String) {
        _uiState.update {
            it.copy(selectedColor = color)
        }
    }

    fun onImageChange(index: Int) {
        _uiState.update {
            it.copy(selectedImageIndex = index)
        }
    }
}